//
//  PACardAuthViewController.m
//  PAMobileWallet
//
//  Created by Pay_SMP002 on 13-7-4.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PACardAuthViewController.h"
#import "Global.h"
#import "PAConstants.h"
#import "PACardAuthView.h"

#import "PAPersonalViewController.h"

#import "PACardAuthViewController.h"
#import "PATextFieldCell.h"
#import "UIColor+Extend.h"
#import "PASelfInfo.h"
#import "PAChekText.h"
#import "PADataCenter.h"
#import "PANetworkManager.h"
#import "PAPersonalCenterView.h"
#import "PAReadagreementViewController.h"
#import "PAChargeMoneyViewController.h"
#import "PAStateType.h"
#import "PAChekText.h"
#import "PAPersonalViewController.h"
#import "PARemitMoneyViewController.h"
#import "PABankCardInfo.h"

unsigned int secondsT = GET_VALID_CODE_TIMER;

@interface PACardAuthViewController ()

@end

@implementation PACardAuthViewController
@synthesize cardTableView;
@synthesize dismissTypeString;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self){
        cardAuthView = [[PACardAuthView alloc] initWithFrame:RECT_PHONE];
        cardAuthView.parentController = self;
        self.view = cardAuthView;

        cardAuthView.chekTF.delegate =self;
        cardAuthView.cardNumTF.delegate= self;
        
        cardTableView = [[UITableView alloc] initWithFrame:CGRectMake(5, 44+10, 310, 400) style:UITableViewStyleGrouped];
        cardTableView.delegate = self;
        cardTableView.dataSource = self;
        cardTableView.backgroundView = nil;
        cardTableView.backgroundColor = [UIColor clearColor];
        [cardAuthView addSubview:cardTableView];
        
        navView = [[PANavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        navView.delegate = self;
        [navView setTitle:@"银行卡认证"];
        [cardAuthView addSubview:navView];
        
        accountArray = [[NSMutableArray alloc] initWithObjects:@"姓名:",@"证件号码:", nil];
        tfnameArray = [[NSMutableArray alloc] initWithObjects:@"此卡在银行预留手机号",@"短信校验码", nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeStateType:) name:@"changeStateType" object:nil];
    }
    return self;
}

- (void)changeStateType:(NSNotification *)notification
{
    self.dismissTypeString = [notification object];
}

- (void)sendCardMark:(NSString *)getCardMark sendCardNum:(NSString *)getCardNum sendType:(NSString *)getType sendFullName:(NSString *)getFullName
{
    bankCardMark = getCardMark;
    bankCardNumT = getCardNum;
    bankCardType = getType;
    bankCardFullName = getFullName;
    
    cardAuthView.bankNameLable.text = @"";
    cardAuthView.bankNumLable.text = @"";
    cardAuthView.cardNumTF.text = @"";
    cardAuthView.cardNumTF.text = @"";
    
    cardMarkArray = [BANKCARD_MARK componentsSeparatedByString:@","]; //本地银行名字（简写）
    for (int i = 0; i < [cardMarkArray count]; i++)
    {
        NSString * cardMarkString = [cardMarkArray objectAtIndex:i];
        if ([bankCardMark isEqualToString:cardMarkString])
        {
            cardAuthView.markImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"a%@.png",cardMarkString]];
            break;
        }
    }

    cardAuthView.bankNameLable.text = bankCardType;
    cardAuthView.bankNumLable.text = bankCardNumT;

    [self.cardTableView reloadData];
}

#pragma mark - PANavViewDelegate methods

- (void)sendSelf:(PANavView *)sendView
{
    [self.navigationController popViewControllerAnimated:YES];
}

//短信验证
- (void)checkMessage:(id)sender
{
    NSMutableDictionary * postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_apply_sms_code",k_loginId:cardAuthView.chekTF.text,k_useType:[NSNumber numberWithInt:2],k_phoneNum:cardAuthView.chekTF.text}];
    [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];

    messageTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
}

- (void)testNext:(id)sender
{
    UIButton * receiveButton = (UIButton *)sender;
    if (receiveButton.tag == 30)  // 阅读协议条款
    {
        if (!readagreementViewController)
        {
            readagreementViewController = [[PAReadagreementViewController alloc] init];
            readagreementViewController.parentController = self;
        }
        
        [readagreementViewController sendShowType:2];
        [self.navigationController presentViewController:readagreementViewController animated:YES completion:nil];
    }
    else if (receiveButton.tag == 40)  // 下一步（验证验证码）
    {
        NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_confirm_sms_code",k_loginId:cardAuthView.chekTF.text,k_useType:[NSNumber numberWithInt:2],k_messageCode:cardAuthView.cardNumTF.text}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
    }
}

- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    NSString *op = [responsDic objectForKey:k_operationType];
    if ([op isEqualToString:@"op_apply_sms_code"]){
        [cardAuthView.cardNumTF becomeFirstResponder];
    }
    if ([op isEqualToString:@"op_confirm_sms_code"]){
        /*
         * 手动拉取已经绑定银行卡信息
         */
        NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_query_bank_card"}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];

    }
    if ([op isEqualToString:@"op_query_bank_card"]){
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"恭喜您！已开通快捷支付" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        alert.tag = 100;
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 100 && buttonIndex == 0)
    {
        NSArray *controllers = [self.navigationController viewControllers];
        
        if([[PAStateType sharedInstance].personalOrCharge isEqualToString:@"20"] || [[PAStateType sharedInstance].personalOrCharge isEqualToString:@"40"]){
            for (PABaseViewController *controller in controllers){
                if ([controller isKindOfClass:[PAChargeMoneyViewController class]]){
                    chargeMoneyViewController = (PAChargeMoneyViewController *)controller;
                }
            }
            if ([[PADataCenter sharedInstance].selfInfo.bankCardInfos count]>0) {
                
                for (int i = 0; i<[[PADataCenter sharedInstance].selfInfo.bankCardInfos count]; i++) {
                    PABankCardInfo * bankCardInfo = [[PADataCenter sharedInstance].selfInfo.bankCardInfos objectAtIndex:i];
                    if ([bankCardInfo.bankCardNum isEqualToString:bankCardFullName]){
                        [[NSNotificationCenter defaultCenter] postNotificationName:NOT_SelectedCard  object:bankCardInfo];
                        break;
                    }
                    //                        else{
                    //                            PABankCardInfo * bankCardInfoOne = [[PADataCenter sharedInstance].selfInfo.bankCardInfos objectAtIndex:0];
                    //                            [[NSNotificationCenter defaultCenter] postNotificationName:NOT_SelectedCard  object:bankCardInfoOne];
                    //                        }
                }
                [[PAStateType sharedInstance] setValue:@"100" forKey:@"personalOrCharge"];
                [self.navigationController popToViewController:chargeMoneyViewController animated:YES];
            }
        }
        else if([[PAStateType sharedInstance].personalOrCharge isEqualToString:@"30"]){
            for (PABaseViewController *controller in controllers){
                if ([controller isKindOfClass:[PARemitMoneyViewController class]]){
                    remitMoneyViewController = (PARemitMoneyViewController *)controller;
                }
            }
            [[PAStateType sharedInstance] setValue:@"100" forKey:@"personalOrCharge"];
            [self.navigationController popToViewController:remitMoneyViewController animated:YES];
        }else{
            for (PABaseViewController *controller in controllers){
                if ([controller isKindOfClass:[PAPersonalViewController class]]){
                    personalViewController = (PAPersonalViewController *)controller;
                }
            }
            [[PAStateType sharedInstance] setValue:@"100" forKey:@"personalOrCharge"];
            [self.navigationController popToViewController:personalViewController animated:YES];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

#pragma mark - UITableViewDelegate methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (1==section)
    {
        return 2;
    }
    else
    {
        return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 4)
    {
        return 40.0f;
    }
    if (section == 1)
    {
        return 0.0f;
    }
    if (section == 5)
    {
        return 49.0f;
    }
    else
    {
        return 50.0f;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (0 == section)
    {
        return cardAuthView.view_one;
    }
    if (2 == section)
    {
        return cardAuthView.view_three;
    }
    if (3 == section)
    {
        return cardAuthView.view_four;
    }
    if (4 == section)
    {
        return cardAuthView.view_five;
    }
    if (5 == section)
    {
        return cardAuthView.nextButton;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    PATextFieldCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (nil == cell)
    {
        cell = [[PATextFieldCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //点击是后边显示的类型
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (indexPath.section == 1)
    {
        cell.nameLable.text = [accountArray objectAtIndex:indexPath.row];
        
        if (indexPath.row == 0)
        {
            cell.typeLable.text = [PADataCenter sharedInstance].selfInfo.baseInfo.realName;
            
            cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_account2.png"]];
        }
        if (indexPath.row == 1)
        {
            cell.typeLable.text = [NSString stringWithFormat:@"%@*********%@",[(NSString *)[PADataCenter sharedInstance].selfInfo.idCardNo substringToIndex:4],[(NSString *)[PADataCenter sharedInstance].selfInfo.idCardNo substringFromIndex:[[PADataCenter sharedInstance].selfInfo.idCardNo length]-4] ];
            cell.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"login_password2.png"]];
        }
    }
    
    return cell;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (self.cardTableView.contentOffset.y<122.0f && self.cardTableView.contentOffset.y>0.0f) {
        [cardAuthView.chekTF resignFirstResponder];
        [cardAuthView.cardNumTF resignFirstResponder];
        [self.cardTableView setContentOffset:CGPointMake(0, 0)];
    }
}

#pragma mark - UITextFieldDelegate  methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //self.cardTableView.frame = CGRectMake(5, 44+10, 310, 400);
    [self.cardTableView setContentOffset:CGPointMake(0, 0)];

    [textField resignFirstResponder];
    
    return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag == 30)
    {
        //self.cardTableView.frame = CGRectMake(5, 44+10 - (iPhone5?100:170) - 5, 310, 400);
        [self.cardTableView setContentOffset:CGPointMake(0, (iPhone5?100:170)-44-5)];

        cardAuthView.chekTFBgImage.image = [UIImage imageNamed:@"textbox.png"];
        cardAuthView.cardNumTFImage.image = [UIImage imageNamed:@"textbox2.png"];
    }
    else if (textField.tag == 40)
    {
        //self.cardTableView.frame = CGRectMake(5, 44+10 - (iPhone5?0:170) - 5, 310, 400);
        [self.cardTableView setContentOffset:CGPointMake(0, (iPhone5?100:170)-44-5)];
        cardAuthView.chekTFBgImage.image = [UIImage imageNamed:@"textbox2.png"];
        cardAuthView.cardNumTFImage.image = [UIImage imageNamed:@"textbox.png"];
    }
    else
    {
        //self.cardTableView.frame = CGRectMake(5, 44+10, 310, 400);
        [self.cardTableView setContentOffset:CGPointMake(0, 0)];
    }
}

//倒计时方法
-(void)timerFireMethod:(NSTimer *)theTimer
{
    if (secondsT == 1)
    {
        [theTimer invalidate];
        secondsT = GET_VALID_CODE_TIMER;
        [cardAuthView.checkButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cardAuthView.checkButton setBackgroundImage:[UIImage imageNamed:@"card_check3.png"] forState:UIControlStateNormal];
        [cardAuthView.checkButton setEnabled:YES];
        [cardAuthView.checkButton setTintColor:[UIColor darkTextColor]];
        cardAuthView.checkButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    }else
    {
        secondsT--;
        NSString * title = [NSString stringWithFormat:MSG_DYNAMIC_CODE_WAIT,secondsT];
        [cardAuthView.checkButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [cardAuthView.checkButton setBackgroundImage:[UIImage imageNamed:@"card_check4.png"] forState:UIControlStateNormal];
        [cardAuthView.checkButton setEnabled:NO];
        cardAuthView.checkButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        [cardAuthView.checkButton setTitle:title forState:UIControlStateNormal];
    }
}

- (void)releaseTImer
{
    if (messageTimer)
    {
        if ([messageTimer respondsToSelector:@selector(isValid)])
        {
            if ([messageTimer isValid])
            {
                [messageTimer invalidate];
                secondsT = GET_VALID_CODE_TIMER;
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    cardAuthView.cardNumTFImage.image = [UIImage imageNamed:@"textbox.png"];
    cardAuthView.cardNumTFImage.image = [UIImage imageNamed:@"textbox.png"];
    
    cardAuthView.agreeButton.selected = NO;
    [cardAuthView.agreeButton setBackgroundImage:[UIImage imageNamed:@"register_seclectYES.png"] forState:UIControlStateNormal];
    
    [cardAuthView.chekTF resignFirstResponder];
    [cardAuthView.cardNumTF resignFirstResponder];
    cardAuthView.chekTF.delegate = self;
    cardAuthView.cardNumTF.delegate = self;
    
    if (dismissTypeString && ![self.dismissTypeString isEqualToString:@"dismiss"]) {
        cardAuthView.checkButton.enabled = NO;
        cardAuthView.checkButton.selected = NO;
        [cardAuthView.checkButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cardAuthView.checkButton setBackgroundImage:[UIImage imageNamed:@"card_check4.png"] forState:UIControlStateNormal];
        [cardAuthView.checkButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        cardAuthView.checkButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
        
        cardAuthView.nextButton.enabled = NO;
        [cardAuthView.nextButton setBackgroundImage:[UIImage imageNamed:@"button_B1.png"] forState:UIControlStateNormal];
        
        cardAuthView.chekTF.text = @"";
        cardAuthView.cardNumTF.text = @"";
        
        [self releaseTImer];
    }
    
    //self.cardTableView.frame = CGRectMake(5, 44+10, 310, 400);

    [self.cardTableView setContentOffset:CGPointMake(0, 0)];

    [cardAuthView.chekTF addTarget:self action:@selector(changeCheckButtonState:) forControlEvents:UIControlEventEditingChanged];
    [cardAuthView.cardNumTF addTarget:self action:@selector(changeNextButtonState:) forControlEvents:UIControlEventEditingChanged];
    
    stateTypeString = @"";
    stateTypeString = [PAStateType sharedInstance].personalOrCharge;
}

- (void)changeCheckButtonState:(UITextField *)getUserNameTF
{
    //if ([cardAuthView.chekTF.text length] == 11)
    if ([PAChekText validMobileNo:cardAuthView.chekTF.text]==1) 
    {
        cardAuthView.checkButton.enabled = YES;
        [cardAuthView.checkButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cardAuthView.checkButton setBackgroundImage:[UIImage imageNamed:@"card_check3.png"] forState:UIControlStateNormal];
    }
    else
    {
        secondsT = GET_VALID_CODE_TIMER;
        [self releaseTImer];

        cardAuthView.checkButton.enabled = NO;
        [cardAuthView.checkButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [cardAuthView.checkButton setBackgroundImage:[UIImage imageNamed:@"card_check4.png"] forState:UIControlStateNormal];
    }
    
    [cardAuthView.checkButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    cardAuthView.checkButton.titleLabel.font = [UIFont systemFontOfSize:15.0f];
    
    cardAuthView.nextButton.enabled = NO;
    [cardAuthView.nextButton setBackgroundImage:[UIImage imageNamed:@"button_B1.png.png"] forState:UIControlStateNormal];
}

- (void)changeNextButtonState:(UITextField *)getMessageTF
{
    if ([PAChekText validVerificationCode:cardAuthView.cardNumTF.text]==1 && cardAuthView.agreeButton.selected == NO)
    {
        cardAuthView.nextButton.enabled = YES;
        [cardAuthView.nextButton setBackgroundImage:[UIImage imageNamed:@"button_A1.png"] forState:UIControlStateNormal];
        [cardAuthView.nextButton setBackgroundImage:[UIImage imageNamed:@"button_A2.png"] forState:UIControlStateHighlighted];
        [cardAuthView.nextButton setTitleColor:ABLE_COLOR forState:UIControlStateNormal];
        [cardAuthView.nextButton setTitleColor:ABLE_COLOR forState:UIControlStateHighlighted];

        [cardAuthView.cardNumTF resignFirstResponder];

        //self.cardTableView.frame = CGRectMake(5, 44+10, 310, 400);
        [self.cardTableView setContentOffset:CGPointMake(0, 0)];

    }else{
        cardAuthView.nextButton.enabled = NO;
        [cardAuthView.nextButton setBackgroundImage:[UIImage imageNamed:@"button_B1.png.png"] forState:UIControlStateNormal];
        cardAuthView.nextButton.titleLabel.textColor = ENABLE_COLOR;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
